package my_log

import (
	"encoding/json"
	"fmt"
	"go-utils/my_log/my_log_interface"
	"go-utils/struct_util"
	"io"
	"time"
)

const (
	Info    = "info"
	Warning = "warning"
	Error   = "error"
)

type BaseLog struct {
	Type      string `json:"type"` //日志的类型，不同的值对应不同的结构体
	Level     string `json:"level"`
	Message   string `json:"message"`
	Time      string `json:"time"`
	TimeStamp int64  `json:"timeStamp"`
}
type MyLog struct {
	w io.Writer
}

func CreateMyLog(w io.Writer) my_log_interface.Interface {
	return &MyLog{
		w: w,
	}
}

var su = struct_util.CreateStructUtil()

// write 把logInfo写入
func (l *MyLog) write(li interface{}) {
	bm, _ := su.GetFieldValue(li, "BaseLog")

	_ = su.ModifyField(bm, "Time", time.Now().Format("2006-01-02 15:04:05"))
	_ = su.ModifyField(bm, "TimeStamp", time.Now().UnixMilli())

	b, _ := json.Marshal(li)

	_, err := l.w.Write(append(b, []byte("\n")...))
	if err != nil {
		fmt.Println("log write error:", err.Error())
	}

}

// Info cl refers to concreteLogInfo
func (l *MyLog) Info(cl interface{}) {
	bm, _ := su.GetFieldValue(cl, "BaseLog")
	_ = su.ModifyField(bm, "Level", Info)
	l.write(cl)
}
func (l *MyLog) Warning(cl interface{}) {
	bm, _ := su.GetFieldValue(cl, "BaseLog")
	_ = su.ModifyField(bm, "Level", Warning)
	l.write(cl)
}
func (l *MyLog) Error(cl interface{}) {
	bm, _ := su.GetFieldValue(cl, "BaseLog")
	_ = su.ModifyField(bm, "Level", Error)
	l.write(cl)
}
